//
//  BuySiteTicketViewController.m
//  EasyToo
//
//  Created by Jr Lan on 13-9-1.
//
//

#import "BuySiteTicketViewController.h"
#import "SiteConfirmViewController.h"
#import "NetworkAlertView.h"
#import <QuartzCore/QuartzCore.h>

@interface BuySiteTicketViewController ()

@end

@implementation BuySiteTicketViewController
{
    UITextField *_countTF;
    
    UIButton *_zfbButton;
    UIButton *_ybButton;
    
    NSInteger _payType;
    
    UITextField *_dateTF;
    UIDatePicker *_datePicker;
    NSLocale *_datelocale;
    
    UITextField *_phoneTF;
    UITextField *_truenameTF;
    
    UIAlertView *_baseAlert;
}

- (void)dealloc
{
    [_countTF release];
    [_zfbButton release];
    [_ybButton release];
    [_dateTF release];
    [_datePicker release];
    [_datelocale release];
    [_phoneTF release];
    [_truenameTF release];
    
    _countTF = nil;
    _zfbButton = nil;
    _ybButton = nil;
    _dateTF = nil;
    _datePicker = nil;
    _datelocale = nil;
    _phoneTF = nil;
    _truenameTF = nil;
    
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //初始化视图
    [self init_view];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//初始化视图
- (void)init_view
{
    self.title = @"景点票";
    //加载背影
     [self.view setBackgroundColor:BackgroundColor];
    
    int width = [DeviceUtil getScreenWidth];
    int heigth = self.view.frame.size.height;
    
    UIScrollView *myscrollview = [[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, width, heigth)]autorelease];
    myscrollview.directionalLockEnabled = YES; //只能一个方向滑动
    myscrollview.pagingEnabled = NO; //是否翻页
    myscrollview.backgroundColor = [UIColor whiteColor];
    myscrollview.showsVerticalScrollIndicator =YES; //垂直方向的滚动指示
    myscrollview.indicatorStyle = UIScrollViewIndicatorStyleWhite;//滚动指示的风格
    myscrollview.showsHorizontalScrollIndicator = NO;//水平方向的滚动指示
    myscrollview.delegate = self;
    CGSize newSize = CGSizeMake(width, 1000);
    [myscrollview setContentSize:newSize];
    
    UIControl *control = [[[UIControl alloc] initWithFrame:myscrollview.frame] autorelease];
    [myscrollview addSubview:control];
    [control addTarget:self action:@selector(onBackgroudTouch) forControlEvents:UIControlEventTouchDown];

    
    //加载票务信息
    [self initTicket:myscrollview];
    
    //出游日期
    [self init_view_date:myscrollview];
    
    //手机号码
    _truenameTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 220, 280, 50)];
    _truenameTF.text = @"";
    _truenameTF.placeholder = @"旅客真实姓名";
    _truenameTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _truenameTF.borderStyle = UITextBorderStyleRoundedRect;
    _truenameTF.delegate = self ;
    _truenameTF.returnKeyType =UIReturnKeyDone;
    _truenameTF.layer.borderColor = [UIColor grayColor].CGColor;
    _truenameTF.layer.borderWidth = 1 ;
    _truenameTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_truenameTF];
    
    //手机号码
    _phoneTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 280, 280, 50)];
    _phoneTF.text = @"";
    _phoneTF.placeholder = @"请输入手机号码";
    _phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    _phoneTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _phoneTF.borderStyle = UITextBorderStyleRoundedRect;
    _phoneTF.delegate = self ;
    _phoneTF.returnKeyType =UIReturnKeyDone;
    _phoneTF.layer.borderColor = [UIColor grayColor].CGColor;
    _phoneTF.layer.borderWidth = 1 ;
    _phoneTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_phoneTF];
    
    //支付方式
    UILabel *label_pay = [[[UILabel alloc]initWithFrame:CGRectMake(10, 340, 180, 30)]autorelease];
    label_pay.backgroundColor = [UIColor clearColor];
    label_pay.text = @"选择支付方式:";
    [myscrollview addSubview:label_pay];
    
//    _zfbButton = [[UIButton alloc] initWithFrame:CGRectMake(30, 380, 100, 30)];
//    [_zfbButton setBackgroundImage:[UIImage imageNamed:@"zfb.png"] forState:UIControlStateNormal];
//    [_zfbButton setBackgroundImage:[UIImage imageNamed:@"zhifubao2.png"] forState:UIControlStateSelected];
//    [_zfbButton addTarget:self action:@selector(zfbButtonPick:) forControlEvents:UIControlEventTouchDown];
//    [myscrollview addSubview:_zfbButton];
    
    _ybButton = [[UIButton alloc] initWithFrame:CGRectMake(30, 380, 100, 30)];
    [_ybButton setBackgroundImage:[UIImage imageNamed:@"yinlian1"] forState:UIControlStateNormal];
    [_ybButton setBackgroundImage:[UIImage imageNamed:@"yinlian2"] forState:UIControlStateSelected];
    [_ybButton addTarget:self action:@selector(ybButtonPick:) forControlEvents:UIControlEventTouchDown];
    [myscrollview addSubview:_ybButton];
    
    
    UIButton *nextStep =[UIButton buttonWithType:UIButtonTypeCustom];
    nextStep.frame = CGRectMake(40, 420, 230, 40);
    [nextStep setBackgroundImage:[UIImage imageNamed:@"xyb"] forState:UIControlStateNormal];
    [nextStep setTitle:@"下一步" forState:UIControlStateNormal];
    nextStep.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    nextStep.layer.borderColor = [UIColor grayColor].CGColor;
    nextStep.layer.borderWidth = 1 ;
    nextStep.layer.cornerRadius = 10 ;
    [myscrollview addSubview:nextStep];
    [nextStep addTarget:self action:@selector(confirmMessge:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:myscrollview];
}

//加载票务信息
- (void) initTicket:(UIScrollView*)myscrollview
{
    //加载图片
    UIImageView *imgView = [[[UIImageView alloc] initWithFrame:CGRectMake(10, 20, 300, 130)]autorelease];
    imgView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    imgView.image = [UIImage imageNamed:@"actingtickets_03"];
    [myscrollview addSubview:imgView];

    //加载说明
    UILabel *desclbl = [[[UILabel alloc]initWithFrame:CGRectMake(40, 20, 240, 30)]autorelease];
    desclbl.text = self.allSiteInfo.sceneName;
    desclbl.font = [UIFont systemFontOfSize:15];
    desclbl.backgroundColor = [UIColor clearColor];
    desclbl.adjustsFontSizeToFitWidth = YES;
    [myscrollview addSubview:desclbl];
    
    //加载门票
    UILabel *cinemalbl = [[[UILabel alloc]initWithFrame:CGRectMake(40, 50, 240, 30)]autorelease];
    cinemalbl.text = self.siteTicketInfo.sceneTicketName;
    cinemalbl.font = [UIFont systemFontOfSize:15];
    cinemalbl.backgroundColor = [UIColor clearColor];
    cinemalbl.adjustsFontSizeToFitWidth = YES;
    cinemalbl.lineBreakMode = UILineBreakModeWordWrap;
    cinemalbl.numberOfLines = 0;
    cinemalbl.textAlignment = NSTextAlignmentLeft;
    [myscrollview addSubview:cinemalbl];
    
    //加载价格
    UILabel *cinemalbl2 = [[[UILabel alloc]initWithFrame:CGRectMake(40, 80, 240, 30)]autorelease];
    cinemalbl2.text = [NSString stringWithFormat:@"单价：￥%@", self.siteTicketInfo.salePrice];
    cinemalbl2.font = [UIFont systemFontOfSize:15];
    cinemalbl2.backgroundColor = [UIColor clearColor];
    cinemalbl2.adjustsFontSizeToFitWidth = YES;
    cinemalbl2.lineBreakMode = UILineBreakModeWordWrap;
    cinemalbl2.numberOfLines = 0;
    cinemalbl2.textAlignment = NSTextAlignmentLeft;
    [myscrollview addSubview:cinemalbl2];
    
    //加载数量
    UILabel *countlbl = [[[UILabel alloc]initWithFrame:CGRectMake(40, 110, 40, 30)]autorelease];
    countlbl.text = @"数量：";
    countlbl.font = [UIFont systemFontOfSize:15];
    countlbl.backgroundColor = [UIColor clearColor];
    countlbl.adjustsFontSizeToFitWidth = YES;
    countlbl.textAlignment = NSTextAlignmentCenter;
    [myscrollview addSubview:countlbl];
    
    //加载加号
    UIButton *plusbtn =[UIButton buttonWithType:UIButtonTypeCustom];
    plusbtn.frame = CGRectMake(90, 112, 30, 25);
    [plusbtn setBackgroundImage:[UIImage imageNamed:@"heng"] forState:UIControlStateNormal];
    [myscrollview addSubview:plusbtn];
    [plusbtn addTarget:self action:@selector(plusEvent) forControlEvents:UIControlEventTouchUpInside];
    
    //加载数量
    _countTF = [[UITextField alloc] initWithFrame:CGRectMake(130, 112, 40, 25)];
    _countTF.text = @"2";
    [_countTF setBorderStyle:UITextBorderStyleBezel];
    _countTF.backgroundColor = [UIColor whiteColor];
    [_countTF setEnabled:NO];
    [myscrollview addSubview:_countTF];
    
    //加载减号
    UIButton *minusbtn =[UIButton buttonWithType:UIButtonTypeCustom];
    minusbtn.frame = CGRectMake(180, 112, 30, 25);
    [minusbtn setBackgroundImage:[UIImage imageNamed:@"heng"] forState:UIControlStateNormal];
    [myscrollview addSubview:minusbtn];
    [minusbtn addTarget:self action:@selector(minusEvent) forControlEvents:UIControlEventTouchUpInside];
}


//出发日期
- (void)init_view_date:(UIScrollView*)myscrollview
{
    _dateTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 160, 280, 50)];
    _dateTF.text = @"";
    _dateTF.placeholder = @"选择出游日期";
    _dateTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _dateTF.borderStyle = UITextBorderStyleRoundedRect;
    _dateTF.delegate = self ;
    _dateTF.returnKeyType =UIReturnKeyDone;
    _dateTF.layer.borderColor = [UIColor grayColor].CGColor;
    _dateTF.layer.borderWidth = 1 ;
    _dateTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_dateTF];
    
    // 建立 UIDatePicker
    _datePicker = [[UIDatePicker alloc]init];
    
    // 時區的問題請再找其他協助 不是本篇重點
    _datelocale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_TW"];
    _datePicker.locale = _datelocale;
    _datePicker.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
    _datePicker.datePickerMode = UIDatePickerModeDate;
    
    // 以下這行是重點 (螢光筆畫兩行) 將 UITextField 的 inputView 設定成 UIDatePicker
    // 則原本會跳出鍵盤的地方 就改成選日期了
    _dateTF.inputView = _datePicker;
    
    // 建立 UIToolbar
    UIToolbar *_toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 420, 44)];
    
    // 選取日期完成鈕 並給他一個 selector
    UIBarButtonItem *_right = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(cancelPicker)];
    
    // 把按鈕加進 UIToolbar
    _toolBar.items = [NSArray arrayWithObject:_right];
    
    // 以下這行也是重點 (螢光筆畫兩行)
    // 原本應該是鍵盤上方附帶內容的區塊 改成一個 UIToolbar 並加上完成鈕
    _dateTF.inputAccessoryView = _toolBar;
}


//数量增加
- (void)plusEvent
{
    _countTF.text = [NSString stringWithFormat:@"%d", ([_countTF.text intValue] + 1)];
}

//数量减少
- (void)minusEvent
{
    int count = [_countTF.text intValue];
    if (count > 0) {
        _countTF.text = [NSString stringWithFormat:@"%d", (count - 1)];
    }
}

-(void)zfbButtonPick:(id)sender
{
    [_zfbButton setSelected:YES];
    [_ybButton setSelected:NO];
    _payType = 0;
}

-(void)ybButtonPick:(id)sender
{
    [_zfbButton setSelected:NO];
    [_ybButton setSelected:YES];
    _payType = 1;
}

-(void)confirmMessge:(id)sender
{
    if ([_countTF.text isEqualToString:@"0"]) {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"请选择数量" message:@"票数不能为0哦亲"  delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
        
    } else if([_dateTF.text isEqualToString:@""] || [_truenameTF.text isEqualToString:@""] || [_phoneTF.text isEqualToString:@""]){
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"数据不完整" message:@"请填写完整的数据"  delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
        
    //判断手机号码格式
    }else if ([DeviceUtil isMobileNumber:_phoneTF.text] == NO) {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"手机填错了" message:@"手机号格式出错"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];

    } else{
        SiteConfirmViewController *confirmController = [[SiteConfirmViewController alloc]init];
        confirmController.siteTicketInfo = self.siteTicketInfo;
        confirmController.allSiteInfo = self.allSiteInfo;
        confirmController.count = _countTF.text;
        confirmController.date = _dateTF.text;
        confirmController.name = _truenameTF.text;
        confirmController.phone = _phoneTF.text;
        [self.navigationController pushViewController:confirmController animated:YES];
        [confirmController release];
    }
}

- (void) performDismiss: (NSTimer *)timer {
    [_baseAlert dismissWithClickedButtonIndex:0 animated:NO];//important
    [_baseAlert release];
    _baseAlert = NULL;
}

//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0);//键盘高度216
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    if(offset > 0)
        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
    
    [UIView commitAnimations];
}


//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}


#pragma mark UITextFieldDelegate
#pragma date picker delegate
// 按下完成鈕後的 method
-(void) cancelPicker {
    // endEditing: 是結束編輯狀態的 method
    if ([self.view endEditing:NO]) {
        // 以下幾行是測試用 可以依照自己的需求增減屬性
        NSDateFormatter *formatter = [[[NSDateFormatter alloc] init]autorelease];
        NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:@"yyyy-MM-dd" options:0 locale:_datelocale];
        [formatter setDateFormat:dateFormat];
        [formatter setLocale:_datelocale];
        // 將選取後的日期 填入 UITextField
        _dateTF.text = [NSString stringWithFormat:@"%@",[formatter stringFromDate:_datePicker.date]];
    }
}


#pragma mark UITextFieldDelegate
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_dateTF resignFirstResponder];
    [_truenameTF resignFirstResponder];
    [_phoneTF resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)onBackgroudTouch
{
    [_truenameTF resignFirstResponder];
    [_phoneTF resignFirstResponder];
    [_dateTF resignFirstResponder];
}

@end




